import '@babel/polyfill';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import gsap from 'gsap';
import * as dat from 'dat.gui';

//星系

//场景
const scene = new THREE.Scene();

//相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 200);
camera.position.set(0, 0, 20);
scene.add(camera);

//渲染器
const renderer = new THREE.WebGL1Renderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

//mesh
const cube = new THREE.BoxGeometry(1, 1, 1);
const material1 = new THREE.MeshBasicMaterial({ wireframe: true });
const material2 = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

const cubeArr = new THREE.Group();
for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
        for (let k = 0; k < 5; k++) {
            const mesh = new THREE.Mesh(cube, material1);
            mesh.position.set(i, j, k);
            //scene.add(mesh);
            cubeArr.add(mesh);
            scene.add(cubeArr);
        }
    }
}

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

//intersectObject检测mesh，intersectObjects检测数组arry
window.addEventListener('dblclick', (event) => {
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -((event.clientY / window.innerHeight) * 2 - 1);
    raycaster.setFromCamera(mouse, camera);
    const result = raycaster.intersectObject(cubeArr);
    if (result.length > 0) {
        result[1].object.material = material2;
    } else {
        console.log('没有点击到物体');
    }
});




//控制
const orbitControls = new OrbitControls(camera, renderer.domElement);
orbitControls.enableDamping = true;

//坐标轴
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);


//帧动画
const clock = new THREE.Clock();
function animate() {
    const time = clock.getElapsedTime();
    orbitControls.update();
    renderer.render(scene, camera);
    requestAnimationFrame(animate);
};
animate();

//窗口调整侦听
window.addEventListener('resize', () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
});


